<template>
  <div class="select-cascader-box" :style="selectStyle">
    <el-cascader
      v-model="value"
      :options="optionList"
      v-bind="selectConfig || {}"
      @change="handlerSelectData"
    />
  </div>
</template>

<script>
export default {
  name: 'SelectCascader',
  props: {
    // 筛选样式
    selectStyle: {
      type: Object,
      default: () => ({})
    },
    // 筛选配置
    selectConfig: {
      type: Object,
      default: () => ({})
    },
    // 筛选数据
    selectData: {
      type: Object,
      default: () => ({})
    },
    // 是否重置
    isReset: {
      type: Boolean,
      default: false
    },
    dynamicSelectData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      value: null,
      optionList: []
    }
  },
  watch: {
    'selectData.optionList': {
      handler(option) {
        if (option && option.length > 0) {
          this.optionList = option
          this.handlerDefault('init')
        } else {
          this.optionList = []
        }
      },
      deep: true,
      immediate: true
    },
    isReset() {
      this.handlerDefault('init')
    },
    dynamicSelectData: {
      handler(val) {
        if (val && Object.keys(val).length) {
          const { prop } = this.selectData
          for (const key in val) {
            if (Object.hasOwnProperty.call(val, key) && key === prop) {
              this.value = val[key]
              // this.handlerSelectData(this.value, 'init')
            }
          }
        }
      },
      deep: true
    }
  },
  methods: {
    /**
     * 处理默认值
     */
    handlerDefault() {
      const { defaultConfig } = this.selectData
      this.value = null
      if (defaultConfig) {
        this.value = defaultConfig.value
      }
      if (this.value) {
        this.handlerSelectData(this.value, 'init')
      }
    },
    /**
     * 处理筛选
     * @param {*} val 数据
     * @param {*} type 类型
     */
    handlerSelectData(val, type) {
      const { prop, isClosePop } = this.selectData
      const { props } = this.selectConfig
      const obj = {}
      let curVal = null
      if (props && props.checkStrictly){
        // 单选选择任意一级选项， 返回所选择的各级数据
        curVal = this.value
      }else if (Object.prototype.toString.call(this.value) === '[object Array]') {
        curVal = this.value[this.value.length - 1]
      }
      obj[prop] = curVal || ''
      this.$emit('handlerSelectData', obj, type)
      this.closePop(prop, isClosePop)
    },
    /**
     * 关闭级联弹窗
     */
    closePop(prop, isClosePop) {
      const Ref = this.$refs[prop]
      if (Ref && isClosePop) {
        Ref.dropDownVisible = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.select-cascader-box {
  width: 132px;

  .el-cascader {
    width: 100%;
  }
}
</style>
